﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;

namespace Mvc.XForms.UI {
	public class DefaultGridFormatter : IGridFormatter {
		#region Core

		private const string cssClassFormat = " class=\"{0}\"";
		private const string gridStartFormat = "<table>";
		private const string gridEndFormat = "</table>";

		public virtual string GridStart() {
			return gridStartFormat;
		}

		public virtual string GridEnd() {
			return gridEndFormat;
		}

		#endregion

		#region Head

		private const string headStartFormat = "<thead><tr>";
		private const string headEndFormat = "</tr></thead>";
		private const string sortableFormat = "<th{0}><a title=\"Sort by {1}\" href=\"{2}\">{1}</a></th>";
		private const string sortedAsc = "ascending";
		private const string sortedDesc = "descending";

		public virtual string HeadStart() {
			return headStartFormat;
		}

		public virtual string HeadEnd() {
			return headEndFormat;
		}

		public virtual string HeadSortable(IGridHeadSortable gridHeadSortable) {
			var sortDir = gridHeadSortable.DefaultSortDirection;

			if (gridHeadSortable.IsCurrent) {
				if (gridHeadSortable.Grid.Sorted.SortDirection == SortDirection.Ascending) {
					gridHeadSortable.CssClass.Add(sortedAsc);
					sortDir = SortDirection.Descending;
				} else {
					gridHeadSortable.CssClass.Add(sortedDesc);
					sortDir = SortDirection.Ascending;
				}
			}

			var href = string.Format(gridHeadSortable.Grid.SortedUrlTemplate, gridHeadSortable.SortExpression, (int)sortDir);

			var cssClass = string.Empty;
			if (gridHeadSortable.CssClass.HasClass)
				cssClass = string.Format(cssClassFormat, gridHeadSortable.CssClass);

			var output = string.Format(sortableFormat, cssClass, gridHeadSortable.Label, href);
			return output;
		}

		#endregion

		#region Body

		private const string bodyStartFormat = "<tbody>";
		private const string bodyEndFormat = "</tbody>";
		private const string bodyRowStartFormat = "<tr class=\"{0}\">";
		private const string bodyRowEndFormat = "</tr>";

		public virtual string BodyStart() {
			return bodyStartFormat;
		}

		public virtual string BodyEnd() {
			return bodyEndFormat;
		}

		public virtual string BodyRowStart(int index) {
			var output = string.Format(bodyRowStartFormat, index % 2 == 0 ? "odd" : "even");
			return output;
		}

		public virtual string BodyRowEnd(int index) {
			return bodyRowEndFormat;
		}
		
		#endregion
	}
}